/**
 * 
 */
package us.gaaoc.framework.webapp.backingbeans.agent;

import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;

import us.gaaoc.cms.Exporter;
import us.gaaoc.cms.sustain.vo.CaseFiling;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.CaseRecordStatus;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.util.CaseFilingPersistor;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.util.Messages;

/**
 * @author Sukahda Tapshalkar
 * Jul 2, 2007
 *
 */
public class ExistingFilingPage extends BaseBackingBean {
	
	/** Default Serial Version UID */
	private static final long serialVersionUID = -3325314424627896538L;
	private String docketID;
	private String divisionID;
	private FacesMessage message;
	
	private String courtUuid;
	
	public ExistingFilingPage() {
		courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
	}

	/**
	 * @return the divisionID
	 */
	public String getDivisionID() {
		return divisionID;
	}

	/**
	 * @param divisionID the divisionID to set
	 */
	public void setDivisionID(String divisionID) {
		this.divisionID = divisionID;
	}

	/**
	 * @return the docketID
	 */
	public String getDocketID() {
		return docketID;
	}

	/**
	 * @param docketID the docketID to set
	 */
	public void setDocketID(String docketID) {
		this.docketID = docketID;
	}

	/**
	 * @return the message
	 */
	public FacesMessage getMessage() {
		return message;
	}

	/**
	 * @param message the message to set
	 */
	public void setMessage(FacesMessage message) {
		this.message = message;
	}
	/**
	 * This method is used to add to an existing filing 
	 * @param docketID
	 * @param casDivID
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public String pullCaseFromSustain() throws Exception {
		
		throw new UnsupportedOperationException("Can't pull cases from SUSTAIN");
		
		/*
		String casDivID;
		casDivID = this.divisionID;
	
		boolean validDocketId = this.isValidDocketID(docketID);
		if(validDocketId){
			CaseRecord cr = new CaseRecord();
			// First look for case in GAJE database
			if(casDivID.equalsIgnoreCase("14")){		
				cr = this.getModelFacade().findCaseRecordByDocketID(docketID, courtUuid);
			}else if(casDivID.equalsIgnoreCase("12")){
				cr = this.getModelFacade().findCaseRecordByDocketID(docketID, courtUuid);
			}
			if(cr != null){
				CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(15);
				this.getModelFacade().updateCaseRecordStatus(cr.getUuid(), crs, courtUuid);
				
			}
			else{				
				Map sessionMap = this.getFacesContext()
				.getExternalContext().getSessionMap();
				String courtUuid = (String) sessionMap.get("courtUuid");
			//If not in GAJE system, look in Court's Case Management System
				Exporter export = new Exporter(courtUuid);
				CaseFiling filing = export.doExport(docketID, casDivID,courtUuid,"clerkUuid");
				if (filing != null) {
					if ((filing.getCaseDefendantParty().isEmpty() || (filing.getCaseDefendantParty().size() == 0))
							|| (((filing.getInitatingPartyPersonList().isEmpty() || (filing.getInitatingPartyPersonList().size() == 0))	&& (filing.getCaseInitiatingPartyOrgList().isEmpty() || (filing.getCaseInitiatingPartyOrgList().size() == 0)))
							|| ((filing.getProsecutionAttorneyList().isEmpty()) || (filing.getProsecutionAttorneyList().size() == 0)))) 
					{
						
						FacesContext facesContext = FacesContext
								.getCurrentInstance();
						facesContext
								.addMessage(
										"existingFile:docketID",
										new FacesMessage(
												"Information extracted from court cms is not complete. E-Filing application aborts the operation!"));
						return "stay";

					}
					CaseFilingPersistor cfp = new CaseFilingPersistor();
					
					//Map sessionMap = this.getFacesContext()
					//		.getExternalContext().getSessionMap();
					//String courtUuid = (String) sessionMap.get("courtUuid");
					
					Court court = this.getModelFacade().findCourt(courtUuid);
					cfp.saveToDataModel(filing, court);
			
					//Readd to fix issue:
					//  		b7006e6c-695c-11dd-945f-00301b45ff56			
					//HibernatePhaseListener.getSessionFactory()
					//	.getCurrentSession().getTransaction().commit();
					//-----
					
				}
				else {
					FacesContext facesContext = FacesContext.getCurrentInstance();
					facesContext.addMessage("existingFile:pullCase", new FacesMessage(" No case found in court's cms"));
					return "stay";
				}
			}
		}else {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("existingFile:docketID", new FacesMessage(" Invalid docketId format. Please enter a valid one!"));
			return "stay";
		}
		
		
		/* DivisionId for BibbCounty is 14
		 * and for Washington County is 12 
		 * Search in our mysql database  for the given docketID 
		 * if it is there then change status to "unsentAddition" and show this filing under progressingFiling's table
		 * 
		 * if it is not there then call Angela's sustain method
		 * 
		 * change the status of the documents to "import" after imported into Sustain.
		 */
		
		//return "allFilingPage";
	}
	
	/**
	 * This method validates the docketID entered by the User 
	 * @param context
	 * @param component
	 * @param value
	 * @throws ValidatorException
	 * @throws Exception
	 */
	public void validateDocketID(FacesContext context, UIComponent component,
			Object value) throws ValidatorException, Exception {
		String docketID = (String) value;
		if (!isValidDocketID(docketID.trim())) {
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
	}

	/**
	 * Helper method to validate the docketID entered by the user
	 * @param docketID
	 * @return
	 * @throws Exception
	 */
	protected boolean isValidDocketID(String docketID) throws Exception {
		boolean validField = false;
		char[] charArray = docketID.toCharArray();
		if (!(charArray.length > 10 || charArray.length < 9)) {
			for (char c : charArray) {
				if (!(Character.isDigit(c) || Character.isLetter(c))) {
					message = Messages.getMessage(
							"us.gaaoc.framework.webapp.util.errorMessage",
							"incorrectDocketID", new Object[] { docketID });
					message.setDetail(message.getDetail());
					message.setSeverity(FacesMessage.SEVERITY_ERROR);
					validField = false;
					break;
				} else
					validField = true;
			}
		} else {
			message = Messages.getMessage(
					"us.gaaoc.framework.webapp.util.errorMessage",
					"incorrectDocketID", new Object[] { docketID });
			message.setDetail(message.getDetail());
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
		}
		return validField;
	}

	@SuppressWarnings("unchecked")
	public String back() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		sessionMap.remove("caseUuid");
		return "allFilingPage";
	}

}
